package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.common.constant.StatusConstant;
import com.heima.common.exception.BaseException;
import com.heima.common.result.PageResult;
import com.heima.mapper.PartnerMapper;
import com.heima.pojo.dto.PageDTO;
import com.heima.pojo.entity.Partner;
import com.heima.pojo.vo.PartnerVO;
import com.heima.service.PartnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


/**
 * \* User: chy
 * \* Date: 2025/8/17  10:13
 * \* Description:
 * \
 */
@Service
public class PartnerServiceImpl extends ServiceImpl<PartnerMapper, Partner> implements PartnerService {
    @Autowired
    private PartnerMapper partnerMapper;
    /**
     * 合作商分页查询
     * @param partnerDTO
     * @return
     */
    @Override   //TODO 合作商还有关联的vm设备数量没有写
    public PageResult<PartnerVO> page(PageDTO partnerDTO) {
        PageHelper.startPage(partnerDTO.getPageIndex(),partnerDTO.getPageSize());

        //查询到页面数据
        Page<PartnerVO> partnerPage = partnerMapper.page(partnerDTO);

        long total = partnerPage.getTotal();//总记录数
        Integer totalPage = (int) Math.ceil(total / (double) partnerDTO.getPageSize());//总页数
        List<PartnerVO> result = partnerPage.getResult();//当前页数据

        return PageResult.<PartnerVO>builder()
                .pageIndex(partnerDTO.getPageIndex())
                .pageSize(partnerDTO.getPageSize())
                .totalCount((int) total)
                .totalPage(totalPage)
                .currentPageRecords(result)
                .build();
    }

    /**
     * 新增合作商
     * @param partner
     * @return
     */
    @Override
    public void add(Partner partner) {
        partner.setStatus(StatusConstant.DISABLE);
        String name = partner.getName();
      int i =  partnerMapper.getByName(name);
      if(i>0){
          throw new BaseException("已经存在合作商");
      }
        partnerMapper.add(partner);
    }

    /**
     *  查询合作商
     * @param id
     * @return
     */
    @Override
    public Partner getById(Integer id) {

    Partner  partner = partnerMapper.getById(id);
        return partner;
    }

    /**
     * 删除合作商
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        partnerMapper.deleteById(id);
    }
}
